<template>
  <!-- 设置自动弹出时间段——特殊节假日组件 -->
  <el-row class="usually_box_li" :gutter="8">
    <!-- 名称 -->
    <el-col :span="5">
      <!-- 名称回显 -->
      <span class="content" v-if="!isEdit" style="margin-left: 10px">{{dataObj.name}}</span>
      <!-- 名称设置 -->
      <el-input v-else class="name_edit_input" size="mini" maxlength="6" v-model.trim="dataClone.name" placeholder="如“国庆节”，最多6个字"></el-input>
    </el-col>
    <!-- 日期 -->
    <el-col :span="8" >
      <!-- 日期回显 -->
      <span class="content" v-if="!isEdit" >{{dataObj.dayTitle}}</span>
      <!-- 日期设置 -->
      <el-date-picker
              v-else
              v-model="dataClone.day"
              type="daterange"
              align="right"
              unlink-panels
              size="mini"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions2">
      </el-date-picker>
    </el-col>
    <!-- 非上班时间点 -->
    <el-col :span="8">
      <!-- 非上班时间点回显 -->
      <span class="content" v-if="!isEdit">{{dataObj.weekTimeTitle}}</span>
      <!-- 非上班时间点设置 -->
      <div v-else class="time_edit_box" v-for="(timeLi, index) in dataClone.workTime">
        <!--<div class="time_edit_li">-->
          <!--<el-input class="time_edit_input start_input" size="mini" v-model.trim="timeLi.start" :placeholder="index === 0 ? '如: 09:00' : ''"></el-input>-->
          <!--<el-input class="time_edit_input" size="mini" v-model.trim="timeLi.end"></el-input>-->
        <!--</div>-->
        <el-time-picker
                is-range
                v-model="timeLi.time"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围">
        </el-time-picker>
        <i class="time_edit_btn iconfont" :class="index ? 'icon-zuixiaohua ' : 'icon-zhankai'" @click="todoTimeLi(index)"></i>
      </div>
    </el-col>
    <!-- 操作按钮 -->
    <el-col :span="3">
      <div class="content" v-if="!isEdit">
        <span class="todoBtn update" @click="todoItem('update')">修改</span>
        <span class="todoBtn delete" @click="todoItem('delete')">删除</span>
      </div>
      <div class="content" v-if="isEdit">
        <span class="todoBtn save" @click="todoItem('save')">保存</span>
        <span class="todoBtn cancel" @click="todoItem('cancel')">取消</span>
      </div>
    </el-col>
  </el-row>
</template>
<script>
  import { deepClone, getFormatDateTime } from '@utils/m7Utils.js'
  import bus from '@/store/eventBus'
  export default {
    name: 'addPopSpecialTimeLi',
    data () {
      return {
        pickerOptions2: {     //  非上班时间点快捷选项
          shortcuts: [{
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        currentTodo: 'add',       // 当前操作（'add' || 'edit'）点击取消和保存按钮的时候用到
        dataObj: {                //  默认参数
          name: '',               //  名称
          day: [],               //  日期
          dayTitle: '',          //  日期回显文案
          workTime: [{time: [new Date('2018-12-18 08:00:00'), new Date('2018-12-18 18:00:00')]}],   // 非上班时间点
          weekTimeTitle: ''       //  非上班时间点回显文案
        },
        dataClone: {              //  克隆的参数，暂存用到
          name: '',
          day: [],
          dayTitle: '',
          workTime: [{time: [new Date('2018-12-18 08:00:00'), new Date('2018-12-18 18:00:00')]}],
          weekTimeTitle: ''
        }
      }
    },
    props: {
      data: {         //  当前编辑的数据
        type: Object,
        default: function () {
          return {
            name: '',
            day: [],
            dayTitle: '',
            workTime: [{time: [new Date('2018-12-18 08:00:00'), new Date('2018-12-18 18:00:00')]}],
            weekTimeTitle: ''
          }
        }
      },
      random: {
        type: Number,
        default: function () {
          return 0
        }
      },
      allArray: {
        type: Array,
        default: function () {
          return []
        }
      },
      curIndex: {      //  当前编辑数据的下标
        type: Number,
        default: function () {
          return 0
        }
      },
      isEdit: {     //  当前是否在编辑数据
        type: Boolean,
        default: function () {
          return false
        }
      }
    },
    watch: {
      random () {
        this.dataObj = deepClone(this.data)
      }
    },
    methods: {
      todoItem (type) {     //  增、删、改和取消操作
        let self = this
        let timeArr = []
        if (type === 'update') {
          //  修改数据
          self.currentTodo = 'update'
          let clone = deepClone(self.dataObj)
          clone.workTime.forEach((item, index) => {   //  上班时间点校验
            console.log(item)
            let startTime = '2018-12-18 ' + item.start
            let endTime = '2018-12-18 ' + item.end
            timeArr.push({time: [new Date(startTime), new Date(endTime)]})
          })
          clone.workTime = timeArr
          self.dataClone = clone
//          self.dataClone = deepClone(self.dataObj)
          bus.$emit('changeIsEdit', {index: self.curIndex, data: true, type: 'special'})
        } else if (type === 'delete') {
          //  删除数据
          this.$confirm('确定要删除该项吗？', this.$t('public.tip'), {
            confirmButtonText: this.$t('public.confirm'),
            cancelButtonText: this.$t('public.cancel'),
            cancelButtonClass: 'primary_btn',
            confirmButtonClass: 'primary_btn',
            type: 'warning'
          }).then(() => {
            bus.$emit('deleteLi', {index: self.curIndex, type: 'special'})
          })
        } else if (type === 'save') {
          //  保存数据
          if (!self.dataClone.name) {   //  名称必填校验
            self.$message.error('请输入名称')
            return
          }
          if (!self.dataClone.day.length) {    //  日期必填校验
            self.$message.error('请选择特殊节假日的日期')
            return
          }
          let flag = false
          let timeTitle = ''
          self.dataClone.workTime.forEach((item) => {    //  上班时间点校验
            console.log(getFormatDateTime(item.time[0]))
            let start = getFormatDateTime(item.time[0]).split(' ')[1]
            let end = getFormatDateTime(item.time[1]).split(' ')[1]
            if (!start || !end) {
              //  非空校验
              self.$message.error('请输入上班时间点')
              flag = true
              return false
            }
            timeTitle += start + '-' + end + ', '
            timeArr.push({start: start, end: end})
          })
          if (flag) {
            return
          }
          let repeatFlag = false
          if (self.allArray.length) {
            self.allArray.forEach((item, index) => {
              if (index !== self.curIndex) {
                let weekFlag = false
//                self.dataClone  当前修改的数据       item.data  其它数据
//                当前数据结束 > 其它数据开始   或  当前数据开始  >   其他数据结束   代表没有重合，取反即为重合
                if (!(self.dataClone.day[1] < item.data.day[0] || self.dataClone.day[0] > item.data.day[1])) {
                  weekFlag = true
                }
                if (weekFlag) {                   //  如果日期有重合部分，再判断时间的重合部分
                  timeArr.forEach((cloneWork) => {
                    item.data.workTime.forEach((arrWork) => {
//                      同上
                      if (!(cloneWork.end < arrWork.start || cloneWork.start > arrWork.end)) {
                        repeatFlag = true
                      }
                    })
                  })
                }
              }
            })
          }
          if (repeatFlag) {
            self.$message.error('特殊节假日非上班时间点有重复，请核查')
            return
          }
          self.dataClone.dayTitle = self.dataClone.day[0] + ' 至 ' + self.dataClone.day[1]      //  日期数据回显
          self.dataClone.weekTimeTitle = timeTitle.slice(0, timeTitle.length - 2)                   //  非上班时间点数据回显
          self.dataClone.workTime = timeArr
          bus.$emit('saveLi', {index: self.curIndex, data: self.dataClone, type: 'special'})           // 抛出数据
          self.dataObj = deepClone(self.dataClone)                                                  // 本地保存数据
        } else if (type === 'cancel') {
          //  取消增加||修改
          if (self.currentTodo === 'add') {
            bus.$emit('deleteLi', {index: self.curIndex, type: 'special', todoType: 'add'})
          } else if (self.currentTodo === 'update') {
            bus.$emit('changeIsEdit', {index: self.curIndex, data: false, type: 'special'})
            self.dataClone = {           //  克隆数据初始化
              name: '',
              day: [],
              dayTitle: '',
              workTime: [{time: [new Date('2018-12-18 08:00:00'), new Date('2018-12-18 18:00:00')]}],
              weekTimeTitle: ''
            }
          }
        }
      },
      todoTimeLi (index) {
        //  非上班时间点添加按钮和删除按钮
        if (index === 0) {
          this.dataClone.workTime.push({time: [new Date('2018-12-18 08:00:00'), new Date('2018-12-18 18:00:00')]})
        } else {
          this.dataClone.workTime.splice(index, 1)
        }
      }
    },
    components: {
      bus
    },
    beforeMount () {
      this.dataObj = deepClone(this.data)
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .content
    margin-left 2px
  .todoBtn
    cursor pointer
    margin-right 10px
    color $cf-color1
  .todoBtn.cancel
    color $cf-gray6
  .todoBtn.delete
    color $c-pink
  .tree_input
    input
      width calc(100% - 20px)
      margin-left 10px
  .time_edit_li
    width calc(100% - 14px)
    display inline-block
  .time_edit_input
    width calc(50% - 12px)
    display inline-block
  .time_edit_btn
    cursor pointer
    font-size 12px
    color $cf-color1
    margin-left 6px
  .usually_box_li
    border-bottom 1px solid #E7E7EB
  .usually_box_li:last-child
    border none
  .start_input
    position relative
    margin 0 18px 0 10px
    &:before
      content: ''
      border-top 2px solid $c-border2
      width 10px
      position absolute
      top 18px
      right -14px
  .start_input:nth-child(1)
    margin-left 0
  .auto_popup_time .name_edit_input
    margin-left 10px
    width calc(100% - 10px)
</style>
